import { message } from "@/utils/message";
import { applyProduct } from "@/api/productInfo";
import { computed } from "vue";
import { getExhibitorId } from "@/utils/getExhibitorId";

// 需是hooks写法（函数中有return），避免失去响应性
export function useColumnsHistory(
  productList: any,
  handleRefreshCurrentCallback?: () => void
) {
  const tableDataHistory = computed(() => productList.value || []);
  const columnsHistory: TableColumnList = [
    {
      label: "产品名称",
      prop: "product_name_cn"
    },
    {
      label: "产品配图",
      prop: "product_img",
      cellRenderer: ({ row }) => {
        const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
        const imageUrl = row.product_img
          ? `${BASE_URL}${row.product_img}`
          : "/placeholder-image.png";
        return (
          <img
            src={imageUrl}
            alt="产品配图"
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
          />
        );
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 170,
      cellRenderer: ({ row }) => (
        <>
          <el-button type="danger" round onClick={() => handleDelete(row)}>
            添加到本届
          </el-button>
        </>
      )
    }
  ];

  const handleDelete = async (row: any) => {
    try {
      // 组装申请产品所需数据（根据后端入参调整字段映射）
      const payload: any = {
        // 若历史数据包含这些字段则直接复用
        id: row.id,
        exhibitor_id: getExhibitorId() || 0,
        product_name_cn: row.product_name_cn ?? row.name ?? "",
        product_name_en: row.product_name_en ?? "",
        product_category: row.product_category ?? "",
        product_intr: row.product_intr ?? "",
        product_img: row.product_img ?? row.image ?? "",
        // 新申请默认待提交（或按需要设为0审核中）
        status: 3
      };

      const res: any = await applyProduct(payload);
      if (res?.code === 1) {
        message("添加到本届成功", { type: "success" });
        // 刷新本届列表
        handleRefreshCurrentCallback && handleRefreshCurrentCallback();
      } else {
        message(res?.msg || "添加到本届失败", { type: "error" });
      }
    } catch (e) {
      console.error(e);
      message("添加到本届失败", { type: "error" });
    }
  };

  return {
    columnsHistory,
    tableDataHistory
  };
}
